package object_class;

//equals
class Person {
    private String name;
    private int age;

    public Person(String name,int age) {
        this.name=name;
        this.age=age;
    }


    @Override
    public boolean equals(Object object) {
        if(object==null) {
            return false;
        }
        if(this==object){ //比较二者引用在同一个地址  //调用equals的this不可能是null
            return true;
        }
        if(!(object instanceof Person)) { //子类不是Person类，就返回false
            return false;
        }
        Person person = (Person) object; //向下转型
        //这里的equals比较String类型，已经被系统重写，不再是object的equals
        return this.name.equals(person.name) && this.age==person.age;
    }
}
public class Test {
    public static void main(String[] args) {
        Person person1 = new Person("zhangsan",18);
        Person person2 = new Person("zhangsan",18);

        //System.out.println(person2.equals(person2));

        System.out.println(person1.hashCode());
        System.out.println(person2.hashCode());
    }
}




//hashCode
package object_class;

import java.util.Objects;

class Person {
    private String name;
    private int age;

    public Person(String name,int age) {
        this.name=name;
        this.age=age;
    }

    //重写hashCode
    @Override
    public int hashCode() {
        //计算对象的位置
         return Objects.hash(name,age); //
    }
}
public class Test {
    public static void main(String[] args) {
        Person person1 = new Person("zhangsan",18);
        Person person2 = new Person("zhangsan",18);

        System.out.println(person1.hashCode());
        System.out.println(person2.hashCode());
    }
}